package com.industrial.im.service.impl;


import cn.hutool.core.util.StrUtil;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.im.properties.EmailProperties;
import com.industrial.im.service.EmailSendService;
import com.industrial.im.vo.SendEmailVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.List;
import java.util.Properties;
import com.industrial.im.constant.SendEmailConstant;

@Service("default")
@Slf4j
public class DefaultEmailSendServiceImpl implements EmailSendService {

    @Autowired
    private EmailProperties emailProperties;


    @Override
    public void sendEmail(SendEmailVo vo) throws RuntimeException {
        Properties props = new Properties();
        props.put(SendEmailConstant.MAIL_SMTP_HOST, emailProperties.getHost());
        props.put(SendEmailConstant.MAIL_SMTP_PORT, emailProperties.getPort());
        props.put(SendEmailConstant.MAIL_SMTP_AUTH, emailProperties.getSmtp().getAuth());
        props.put(SendEmailConstant.MAIL_SMTP_STARTTLS_ENABLE, emailProperties.getSmtp().getTlsEnable());
        props.put(SendEmailConstant.MAIL_SMTP_SOCKET_FACTORY_CLASS, emailProperties.getSmtp().getSocketFactory().getClassValue());
        props.put(SendEmailConstant.MAIL_SMTP_SOCKET_FACTORY_FALLBACK, emailProperties.getSmtp().getSocketFactory().getFallback());
        props.put(SendEmailConstant.MAIL_SMTP_SSL_ENABLE, emailProperties.getSmtp().getSslEnable());
        props.put(SendEmailConstant.MAIL_SMTP_CONNECTION_TIMEOUT, emailProperties.getSmtp().getConnectionTimeout());
        props.put(SendEmailConstant.MAIL_SMTP_TIMEOUT, emailProperties.getSmtp().getTimeout());
        props.put(SendEmailConstant.MAIL_SMTP_WRITE_TIMEOUT, emailProperties.getSmtp().getWriteTimeout());


        Session session = Session.getDefaultInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailProperties.getUsername(), emailProperties.getPassword());
            }
        });

        try {
            String[] to = vo.getTo().split(StrUtil.COMMA);
            String[] cc = !StringUtils.isEmpty(vo.getCc()) ? vo.getCc().split(StrUtil.COMMA) : new String[]{};
            String[] bcc = !StringUtils.isEmpty(vo.getBcc()) ? vo.getBcc().split(StrUtil.COMMA) : new String[]{};
            String from = !StringUtils.isEmpty(vo.getFrom()) ? vo.getFrom() : emailProperties.getUsername();
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddresses = InternetAddress.parse(String.join(",", to));
            message.setRecipients(Message.RecipientType.TO, toAddresses);

            if (cc != null && cc.length > 0) {
                InternetAddress[] ccAddresses = InternetAddress.parse(String.join(StrUtil.COMMA, cc));
                message.setRecipients(Message.RecipientType.CC, ccAddresses);
            }

            if (bcc != null && bcc.length > 0) {
                InternetAddress[] bccAddresses = InternetAddress.parse(String.join(StrUtil.COMMA, bcc));
                message.setRecipients(Message.RecipientType.BCC, bccAddresses);
            }

            message.setSubject(vo.getSubject());


            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(vo.getContent(), SendEmailConstant.TEXT_HTML_UTF8);

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            List<File> attachments = vo.getAttachments();
            if(!CollectionUtils.isEmpty(attachments)){
                for (File file : vo.getAttachments()) {
                    MimeBodyPart attachPart = new MimeBodyPart();
                    attachPart.attachFile(file);
                    multipart.addBodyPart(attachPart);
                }
            }
            message.setContent(multipart);
            Transport.send(message);

        } catch (Exception e) {
            log.error("邮件发送失败:{}", e);
        }

    }



}
